package org.shj.spark.streaming;

import java.util.Arrays;
import java.util.Iterator;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;

import scala.Tuple2;

public class HDFSWordCount {

	public static void main(String[] args) throws Exception {
		SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("HDFSWordCount");
		
		//Durations.seconds(5)隐藏的含义：这一批次的Job要在5秒内算完，如果算不完，下一批次的
		//的Job将会延迟执行。如果每个批次的Job都不能在5秒内算完，那么整体延迟就会很大
		JavaStreamingContext jsc = new JavaStreamingContext(conf, Durations.seconds(5));
		
		//注意，此处没有Receiver
		JavaDStream<String> lines = jsc.textFileStream("hdfs://ubuntu1:8020/wordcount_dir");
		//文件目录也可以不写hdfs://ubuntu1:8020，默认也是HDFS上的目录
		//JavaDStream<String> lines = jsc.textFileStream("/wordcount_dir");
		
		JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
			private static final long serialVersionUID = -7561499018426985750L;

			@Override
			public Iterator<String> call(String line) throws Exception {
				return Arrays.asList(line.split(" ")).iterator();
			}
		});
		
		JavaPairDStream<String, Integer> pair = words.mapToPair(new PairFunction<String, String, Integer>() {
			private static final long serialVersionUID = 2823007325722993181L;

			@Override
			public Tuple2<String, Integer> call(String word) throws Exception {
				return new Tuple2<String, Integer>(word, 1);
			}
		});
		
		JavaPairDStream<String, Integer> wordCount = pair.reduceByKey(new Function2<Integer, Integer, Integer>() {
			private static final long serialVersionUID = 8560445270191804880L;

			@Override
			public Integer call(Integer v1, Integer v2) throws Exception {
				return v1 + v2;
			}
		});
		
		wordCount.print();
		
		jsc.start();
		jsc.awaitTermination();
		jsc.close();
	}
	

}
